package com.zdsoft.site.mina.state;

import java.nio.charset.Charset;
import java.util.LinkedList;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilter.NextFilter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineDecoder;

public class CommandDecoder extends TextLineDecoder {
	public CommandDecoder() {
		super(Charset.forName("UTF8"), LineDelimiter.WINDOWS);
	}

	private Object parseCommand(String line) {
		String cmd = line.toLowerCase();
		if (StartCommand.name.equals(cmd)) {
			return new StartCommand();
		} else {
			if (PlayCommand.name.equals(cmd)) {
				return new PlayCommand();
			} else {
				if (StopCommand.name.equals(cmd)) {
					return new StopCommand();
				} else {
					return new UnknownCommand();
				}
			}
		}
	}

	public void decode(IoSession session, IoBuffer in, final ProtocolDecoderOutput out) throws Exception {
		final LinkedList<String> lines = new LinkedList<String>();
		super.decode(session, in, new ProtocolDecoderOutput() {

			@Override
			public void write(Object message) {
				lines.add((String) message);
			}

			@Override
			public void flush(NextFilter arg0, IoSession arg1) {

			}
		});
		for (String s : lines) {
			out.write(parseCommand(s));
		}
	}
}
